package top.zhangjianyong.tools.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class SoHuETFUtil {
    private final static String URL = "https://hq.stock.sohu.com/cn/${type}/cn_${code}-4.html";

    //获取最新价格
    public static SoHuETF getETF(String code) {

        String apiCode = code.replace("sh", "").replace("sz", "");

        String url = URL.replace("${code}", apiCode).replace("${type}", apiCode.substring(3));
        log.info("获取分时量接口URL: {}", url);
        HttpRequest get = HttpUtil.createGet(url);

        try (HttpResponse execute = get.execute()) {
            String body = execute.body();
            log.info("获取分时量接口返回：{}", body);
            String timeDataContent = extractTimeData(body);
            if (null == timeDataContent) return null;
            log.info("提取的 time_data 内容为: {}", timeDataContent);
            JSONArray jsonArray = JSONObject.parseArray(timeDataContent);
            
            // 获取最后一个分时数据（用于获取最新时间和价格）
            JSONArray timeData = jsonArray.getJSONArray(jsonArray.size() - 1);
            String time = timeData.getString(0);
            String value = timeData.getString(1);
            
            // 累加所有分时数据点的成交量（跳过第一个元数据数组）
            long totalVolume = 0;
            int minuteCount = 0;
            for (int i = 1; i < jsonArray.size(); i++) {
                JSONArray item = jsonArray.getJSONArray(i);
                if (item.size() > 3) {
                    String volumeStr = item.getString(3);
                    if (volumeStr != null && !volumeStr.isEmpty()) {
                        try {
                            totalVolume += Long.parseLong(volumeStr);
                            minuteCount++;
                        } catch (NumberFormatException e) {
                            log.warn("解析成交量失败: {}", volumeStr, e);
                        }
                    }
                }
            }
            
            return new SoHuETF(code, time, value, totalVolume, minuteCount);
        }

    }

    @Data
    @AllArgsConstructor
    public static class SoHuETF {
        private String code;
        private String time;
        private String value;
        private Long volume;
        private Integer minuteCount;
    }

    public static String extractTimeData(String body) {
        // 定义正则表达式匹配 time_data(...) 的内容
        Pattern pattern = Pattern.compile("time_data\\(([^)]+)\\)");
        Matcher matcher = pattern.matcher(body);

        if (matcher.find()) {
            // 返回括号内的内容
            return matcher.group(1);
        }
        return null; // 如果未找到匹配项，返回 null
    }

    public static void main(String[] args) {
        SoHuETF value = getETF("sh513050");
        System.out.printf(JSONObject.toJSONString(value));
    }
}
